<?php
class CityModel extends CI_Model
{
    // Mongo
    const collection = 'city';
    const sequence_id = 'city';

    // Cache
    const cache_enable = true;
    const cache_ttl = 86400;
    const prefix_cache_item = 'city.%s';
    const prefix_cache_list = 'city.list.%s.%s.%s';
    const prefix_cache_count = 'city.count.%s.%s';
    

    public function  __construct()
    {
        parent::__construct();
    }

    public function selectCity($id)
    {
        // Check id
        if(empty($id)) return false;

        $data = false;

        // Create cache key
        $cacheKey = sprintf(self::prefix_cache_item, $id);

        // Read cache
        if(self::cache_enable) {
            $data = $this->cache->memcached->get($cacheKey);
        }

        // Check cache
        if($data === false) {

            // Get from BD
            $data = $this->mongo_db->where(array('_id' => $id))->getOne();

            // Write to cache
            $this->cache->memcached->save($cacheKey, $data, 0, self::cache_ttl);
        }

        // Return
        return $data;
    }

    public function selectCityList($stateId , $page)
    {
        // Check stateId
        if(empty($stateId)) return false;

        $list = false;

        // Create cache key
        $cacheKey = sprintf(self::prefix_cache_list, $stateId, $page, FE_CITY_LIMIT);

        // Read cache
        if(self::cache_enable) {
            $list = $this->cache->memcached->get($cacheKey);
        }

        // Check cache
        if($list === false) {

            // Set offset
            $offset = ($page - 1) * FE_CITY_LIMIT;

            // Get from DB
            $list = $this->mongo_db
                    ->where(array('state_id' => $stateId))
                    ->offset($offset)
                    ->limit(FE_CITY_LIMIT)
                    ->order_by(array('_id' => 1))
                    ->get(self::collection);

            // Write to cache
            $this->cache->memcached->save($cacheKey, $list, 0, self::cache_ttl);
        }

        // Return
        return $list;
    }

    public function selectTotalCity($stateId)
    {
        if(empty($stateId)) return false;

        // Create cache key
        $cacheKey = sprintf(self::prefix_cache_count, $stateId);

        $total = false;

        // Read cache
        if(self::cache_enable) {
            $total = $this->cache->memcached->get($cacheKey);
        }

        // Check cache
        if($total === false) {

            // Get from DB
            $total = $this->mongo_db->where(array('state_id' => $stateId))->count(self::collection);

            // Write to cache
            $this->cache->memcached->save($cacheKey, $total, 0, self::cache_ttl);
        }

        // Return
        return $data;
    }
}
?>